package com.zlm.common.util;

import com.alibaba.fastjson.JSONException;
import com.zlm.common.dto.QqResponseDto;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;

/**
 * @Author: duyufu
 * @Date: 2019/4/15 10:27
 */
public class QqUtils {
    public static String getUserInfoUrl = "https://graph.qq.com/user/get_user_info?access_token=%s&oauth_consumer_key" +
            "=1108792110&openid=%s";

    public static QqResponseDto getUserInfo(String accessToken, String openid){
        String qqUrl = String.format(getUserInfoUrl,accessToken,openid);
        URI uri = URI.create(qqUrl);
        HttpClient client = HttpClientBuilder.create().build();
        HttpGet get = new HttpGet(uri);
        try {
            HttpResponse response = client.execute(get);
            if (response.getStatusLine().getStatusCode() == 200) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
                StringBuilder sb = new StringBuilder();
                for (String temp = reader.readLine(); temp != null; temp = reader.readLine()) {
                    sb.append(temp);
                }
                QqResponseDto qqResult = (QqResponseDto)FastJsonUtils.convertJsonToObject(sb.toString(),
                        QqResponseDto.class);
                return qqResult;
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    return null;
    }
}
